package cn.gov.pbc.gd.credit.center.service.user.impl;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.liu.jbase.ResultVo;
import com.liu.jbase.constant.ResCode;
import com.liu.tools.LogUtil;
import com.liu.tools.StrUtil;

import cn.gov.pbc.gd.credit.center.service.user.ICCUserService;
import cn.gov.pbc.gd.credit.center.service.util.JsoupUtil;
import cn.gov.pbc.gd.credit.common.constant.CodeConstant;
import cn.gov.pbc.gd.credit.common.constant.ConfConstant;
import cn.gov.pbc.gd.credit.vo.center.ReqCCUserVo;
import cn.gov.pbc.gd.credit.vo.center.ResCCUserVo;

@Service
public class CCUserServiceImpl implements ICCUserService {

	private static Logger logger = LoggerFactory.getLogger(CCUserServiceImpl.class);
	
	@Override
	public ResultVo<ResCCUserVo> login(ReqCCUserVo vo, HttpServletRequest request) {
		
		ResultVo<ResCCUserVo> resultVo = new ResultVo<>();
		
		if(vo == null || StrUtil.isNull(vo.getPassword(), vo.getUserid())){
			
			logger.error(LogUtil.msg("CCUserServiceImpl:login", "请求参数不正确"));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("登录征信中心失败，请求参数不正确");
			return resultVo;
		}
		
		String data = "userid=" + vo.getUserid()  + "&password=" + vo.getPassword();
		String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccLoginUrl;
		
		try {
			
			
			Document document = null;
			Map<String, String> cookies = null; 
			if(StrUtil.isNotNull(ConfConstant.ccTestPath)){
				   
				 document = Jsoup.parse(new File(ConfConstant.ccTestPath + "登录返回.html"), "UTF-8");
			} else {
				 Connection conn = Jsoup.connect(requestUrl);     
				 conn.method(Method.POST);
				 conn.requestBody(data);
				 conn.followRedirects(false); 
				 conn.postDataCharset("GBK");
				 Response response = conn.execute();
				 String html = response.body();
				 document = Jsoup.parse(html);
				 cookies = response.cookies();
				 logger.info(LogUtil.msg("CCUserServiceImpl:login", "征信中心cookies:" + response.cookies()));
			 }
			 String regx = "(.)*?,欢迎(.)*?";
			 String elements = document.select("b").select("font").last().text();

			 if(! elements.matches(regx)){
				 
				 if(elements.indexOf("修改密码") != -1){
					 logger.error(LogUtil.msg("CCUserServiceImpl:login", "需要修改征信中心用户密码：" + document.html()));
					 resultVo.setCode(CodeConstant.MODIFY_CC_PASSWORD);
					 resultVo.setMsg("需要修改征信中心密码");
					 ResCCUserVo resRealUserLoginVo = new ResCCUserVo();
					 resRealUserLoginVo.setCookies(cookies);
					 resultVo.setData(resRealUserLoginVo);
					 return resultVo;
				 }
				 
				 logger.error(LogUtil.msg("CCUserServiceImpl:login", "登录征信中心失败：" + document.html()));
				 
				 resultVo.setCode(CodeConstant.FAIL);
				 resultVo.setMsg("征信中心" + elements.trim().replace("     ", ""));
				 return resultVo;
			 }
			   
			 ResCCUserVo resRealUserLoginVo = new ResCCUserVo();
			 resRealUserLoginVo.setCookies(cookies);
			 resultVo.setCode(CodeConstant.SUCCESS);
			 resultVo.setData(resRealUserLoginVo);
			 
		} catch (IOException e) {
			
			logger.error(LogUtil.msg("CCUserServiceImpl:login", "登录征信中心异常, userid=" + vo.getUserid()), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("登录征信中心失败");
			return resultVo;
		}
		
		return resultVo;
	}
	
	@Override
	public ResultVo<ResCCUserVo> logout(ReqCCUserVo vo, HttpServletRequest request) {

		ResultVo<ResCCUserVo> resultVo = new ResultVo<>();
		
	    if(vo == null || vo.getCookies() == null){
			
			logger.error(LogUtil.msg("LoginServiceImpl:logout", "请求参数不正确, cookies is null"));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			return resultVo;
		}
		
		String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccLogoutUrl;
  
	    try {
	    	Document document = JsoupUtil.get(requestUrl, "GBK", vo.getCookies());
			logger.debug(LogUtil.msg("LoginServiceImpl:logout", "退出登录结果：" + document.html()));
			
		} catch (Exception e) {
			logger.error(LogUtil.msg("LoginServiceImpl:logout", "退出征信中心异常"), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			return resultVo;
		}    
		
	    resultVo.setCode(CodeConstant.SUCCESS);
	    
		return resultVo;
	}

	@Override
	public ResultVo<ResCCUserVo> modifyPwd(ReqCCUserVo vo, HttpServletRequest request) {

		ResultVo<ResCCUserVo> resultVo = new ResultVo<>();
		
		if(vo == null || vo.getCookies() == null || StrUtil.isNull(vo.getPassword(), vo.getOldpassword(), vo.getNewpasswordvalid())){
			
			logger.error(LogUtil.msg("LoginServiceImpl:modifyPwd", "请求参数不正确"));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("修改密码失败，请求参数不正确");
			return resultVo;
		}
		//8~20个字符，至少包含‘0至9’、‘A至Z’、‘a至z’、‘-_@#’字符中,两种或两种以上的字符
		//passwordflag=1&oldpassword=csmm123456&newpassword=csmm12345&newpasswordvalid=csmm12345
		String data = "passwordflag=1&oldpassword=" + vo.getOldpassword()  + "&newpassword=" + vo.getPassword()
		              + "&newpasswordvalid=" + vo.getNewpasswordvalid();
		String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccModifyPwdUrl;
		String html = "";
		try {

			 Document document = JsoupUtil.post(requestUrl, data, "GBK", vo.getCookies());
			 if(document != null){
				 html = document.html();
				 logger.debug(LogUtil.msg("LoginServiceImpl:modifyPwd", "修改密码返回结果：" + html));
				 if(html.indexOf("密码修改成功") == -1){
					resultVo.setCode(CodeConstant.FAIL);
					resultVo.setMsg("修改密码失败");
					return resultVo;
			     }
			    
				 logger.info(LogUtil.msg("LoginServiceImpl:modifyPwd", "修改密码成功, userid=" + vo.getUserid()));
				
			 }
			 
		} catch (Exception e) {
			
			logger.error(LogUtil.msg("LoginServiceImpl:modifyPwd", "修改密码异常, userid=" + vo.getUserid()), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("修改密码失败");
			return resultVo;
		}
		
		resultVo.setCode(ResCode.SUCCESS);
		return resultVo;
	}

	@Override
	public ResultVo<ResCCUserVo> froceModifyPwd(ReqCCUserVo vo, HttpServletRequest request) {

		ResultVo<ResCCUserVo> resultVo = new ResultVo<>();
		
		if(vo == null || vo.getCookies() == null || StrUtil.isNull(vo.getPassword(), vo.getOldpassword(), vo.getNewpasswordvalid())){
			
			logger.error(LogUtil.msg("LoginServiceImpl:froceModifyPwd", "请求参数不正确"));
			resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
			resultVo.setMsg("修改密码失败，请求参数不正确");
			return resultVo;
		}
		//8~20个字符，至少包含‘0至9’、‘A至Z’、‘a至z’、‘-_@#’字符中,两种或两种以上的字符
		//useridtext=PBC_zhyp&userid=PBC_zhyp&oldpassword=csmm1234&password=csmm123456&confirmpwd=csmm123456
		String data = "useridtext=" + vo.getUserid() + "&userid=" + vo.getUserid()+ ""
				+ "&oldpassword=" + vo.getOldpassword() + "&password=" + vo.getPassword() + "&confirmpwd=" + vo.getNewpasswordvalid();
		String requestUrl = ConfConstant.ccDomainUrl + ConfConstant.ccFroceModifyPwdUrl;
		logger.debug(LogUtil.msg("LoginServiceImpl:froceModifyPwd", "请求url=" + requestUrl));
		String html = "";
		try {

			 Document document = JsoupUtil.post(requestUrl, data, "GBK", vo.getCookies());
			 if(document != null){
				 html = document.html();
				 logger.debug(LogUtil.msg("LoginServiceImpl:froceModifyPwd", "修改密码返回结果：" + html));
				 if(html.indexOf("密码修改成功") == -1){
					resultVo.setCode(CodeConstant.FAIL);
					resultVo.setMsg("修改密码失败");
					return resultVo;
			     }
			    
				 logger.info(LogUtil.msg("LoginServiceImpl:froceModifyPwd", "修改密码成功, userid=" + vo.getUserid()));
				
			 }
			 
		} catch (Exception e) {
			
			logger.error(LogUtil.msg("LoginServiceImpl:froceModifyPwd", "修改密码异常, userid=" + vo.getUserid()), e);
			resultVo.setCode(CodeConstant.EXCEPTION);
			resultVo.setMsg("修改密码失败");
			return resultVo;
		}
		
		resultVo.setCode(ResCode.SUCCESS);
		return resultVo;
	}
	
//	public static void main(String[] args) throws IOException {
//
//		 Document document = Jsoup.parse(new File("E:/征信页面/登录返回.html"), "UTF-8");
//
//		 String regx = "今天(.)*?,欢迎(.)*?登录";
//		 
//		 String elements = document.select("b").select("font").last().text();
//		 
//		 elements.matches(regx);
//		 
//	     System.err.println(elements.matches(regx));			 
//		 
//	}


}
